package noodlog

import (
	"github.com/spf13/cast"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"nood/noodframe/noodconf"
	"os"
	"time"
)

var logger *zap.Logger

func NewZap() {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	core := zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), writeSyncer), zapcore.DebugLevel)
	logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1), zap.Development())
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000")
	encoderConfig.EncodeName = zapcore.FullNameEncoder
	return zapcore.NewJSONEncoder(encoderConfig)
}

func getLogWriter() zapcore.WriteSyncer {
	os.Mkdir("log", 0755) //创建日志目录
	filename := "./log/" + time.Now().Format("2006-01-02") + ".log"
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    cast.ToInt(noodconf.GetToStr("log.maxSize")),
		MaxBackups: cast.ToInt(noodconf.GetToStr("log.maxBackups")),
		MaxAge:     cast.ToInt(noodconf.GetToStr("log.maxAge")),
		Compress:   false,
		LocalTime:  true,
	}
	return zapcore.AddSync(lumberJackLogger)
}

func Debug(msg string, fields ...zap.Field) {
	if logger == nil {
		return
	}
	logger.Debug(msg, fields...)
}

func Error(msg string, fields ...zap.Field) {
	if logger == nil {
		return
	}
	logger.Error(msg, fields...)
}
